<?php

namespace app\admin\service\site;

use app\model\auth\AdminRule;
use app\model\site\SiteUserRule;
use think\Model;

class SiteUserRuleService
{

    private Model $model;

    public function __construct(){
        $this->model = new SiteUserRule();
    }


    /**
     * 多维树形数据
     * @param $data
     * @param int $pid
     * @param int $level
     * @return array
     */
    public function childrenTree($data, int $pid = 0, int $level = 1): array
    {
        $trees = [];
        foreach ($data as $row){

            if($row['pid'] == $pid){
                $row['level'] = $level;
                $row['children'] = $this->childrenTree($data, $row['id'], $level+1);
                $row['hasChildren'] = count($row['children'])>0;
                $row['name'] = lcfirst($row['name']??'');
                $trees[] = $row;
            }
        }
        return $trees;
    }


    /**
     * 一维树形数据
     * @param $data
     * @param int $pid
     * @param int $level
     * @return array
     */
    public function tree($data, int $pid = 0, int $level = 0): array
    {
        $arr = array();
        foreach ($data as $v) {
            if ($v['pid'] == $pid) {
                $v['level']         = $level + 1;
                $v['l_title'] = $v['left_html'] . $v->title;

                // 所有下级的一维数组
                $childrenArr = $this->tree($data, $v['id'], $level + 1);
                $v['hasChildren'] = count($childrenArr)>0;
                $arr[]            = $v->toArray();
                $arr              = array_merge($arr, $childrenArr);
            }
        }
        return $arr;
    }

    public function childrenIds($data, $pid): array
    {
        $arr = array();
        foreach ($data as $v){
            if ($v->pid == $pid){
                $arr[] = $v->id;
                $childrenArr = $this->childrenIds($data, $v->id);
                $arr = array_merge($arr,$childrenArr);
            }
        }
        return $arr;
    }



    /**
     *
     * 权限选项
     *
     */
    public function options(): array
    {

        $data = $this->model->field('id,pid,title,sort')
            ->where('status', 1)
            ->where('rule_type', 'in', [1,2])
            ->order('sort desc')
            ->select();
        return $this->childrenTree($data);
    }

}
